#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Project: devops
#  Author: an00
#  Create: 2018/6/24 15:06

from rest_framework import serializers
from manufacturer.models import Manufacturer, ProductModel


class ManufacturerSerializer(serializers.ModelSerializer):
    """
    使用ModelSerializer时候会使用Model的help_text做帮助提示，verbose_name做label的效果
    ModelSerializer内部封装了create和update方法，外键关联也自动做了，非常方便
    """
    class Meta:
        model = Manufacturer
        fields = '__all__'

    @staticmethod
    def validate_vendor_name(value):
        """
        校验字段，函数名为"validate_" + 模型中字段名，针对单个字段
        :param value:
        :return:
        """
        return value.upper()


class ProductModelSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        vendor = instance.vendor
        result = super().to_representation(instance)
        result['vendor'] = {'id': vendor.id, 'verdor': vendor.vendor_name}
        return result

    def validate(self, attrs):
        """
        限制型号必须全局唯一，方法里通过attrs做验证，可以针对模型中的所有字段
        :param attrs:
        :return:
        """
        manufacturer_obj = attrs['vendor']
        try:
            manufacturer_obj.productmodel_set.get(model_name__exact=attrs['model_name'])
            raise serializers.ValidationError('该型号已经存在.')
        except ProductModel.DoesNotExist:
            return attrs

    class Meta:
        model = ProductModel
        fields = '__all__'
